//ESP_IDF开发组件库使用注意事项：
//  默认条件下,OS tick的周期是10ms,所以通过vTaskDelay来延时2ms是做不到的

#include "main.h"



extern void StatsTask_Init(void);

extern void gatts_demo_init(void);
extern void gattc_demo_init(void);
extern void blufi_Init(void);


volatile char* g_wifi_ssid;
volatile char* g_wifi_password;


//不做通讯的变量
volatile unsigned int ID_first_four = 1234; //MAC初4位做识别
volatile unsigned int ID_mid_four = 1234;   //MAC中间4位做识别
volatile unsigned int ID_last_four = 1234;  //MAC最后4位做识别
//仅上传的变量 Write to AWS
const unsigned char grill_model = 0001;                  //烤炉型号
volatile unsigned int error_state = 0;                   //报错代码 包括料量检测 错误码1 2 4 8 16 上报时累加
volatile signed int global_rtd0_temp = -20;              //RTD温度
volatile unsigned int global_rtd1_temp = 987;            //RTD1温度
volatile unsigned int global_rtd2_temp = 654;            //RTD2温度
volatile unsigned long global_timmer_0_remain = 86400;   //定时器0剩余 用于设置菜单的运行时间
volatile unsigned long global_timmer_1_remain = 86400;   //定时器1剩余
volatile unsigned long global_timmer_2_remain = 86400;   //定时器2剩余
volatile unsigned int firmware_number = 17;            //固件版本号
//上传变量 Write to AWS
volatile unsigned char global_power_switch = 0;     //电源开关
volatile unsigned char global_heat_switch = 0;      //加热开关
volatile unsigned char global_auto_switch = 0;      //自动烧烤模式
volatile unsigned int global_set_temp = 123;        //设置温度
volatile unsigned int global_rtd1_set_temp = 456;   //RTD1报警温度
volatile unsigned int global_rtd2_set_temp = 789;   //RTD2报警温度
volatile unsigned long global_timmer_0_set = 86400; //定时器0设定值 用于设置菜单的运行时间
volatile unsigned long global_timmer_1_set = 86400; //定时器1设定值
volatile unsigned long global_timmer_2_set = 86400; //定时器2设定值
volatile unsigned char global_temp_unit = 0;        //温度单位 0华氏度 1摄氏度
//指令变量 Read from AWS
volatile unsigned char global_power_switch_command = 0;     //电源开关
volatile unsigned char global_heat_switch_command = 0;      //加热开关
volatile unsigned int global_set_temp_command = 123;        //设置温度
volatile unsigned int global_rtd1_set_temp_command = 456;   //RTD1报警温度
volatile unsigned int global_rtd2_set_temp_command = 789;   //RTD2报警温度
volatile unsigned long global_timmer_0_set_command = 86400; //定时器0设定值 用于设置菜单的运行时间
volatile unsigned long global_timmer_1_set_command = 86400; //定时器1设定值
volatile unsigned long global_timmer_2_set_command = 86400; //定时器2设定值
volatile unsigned char global_temp_unit_command = 0;        //温度单位 0华氏度 1摄氏度
volatile unsigned char global_cancel_shutdown_command; //取消熄火

//报警变量
volatile unsigned char global_tmr1_alert = 0;//定时器1报警
volatile unsigned char global_tmr2_alert = 0;//定时器2报警
volatile unsigned char global_rtd1_alert = 0;//肉探针1报警
volatile unsigned char global_rtd2_alert = 0;//肉探针2报警
volatile unsigned char global_rtd0_high_temp_alert = 0;   //肉探针1高温报警
volatile unsigned char global_rtd1_high_temp_alert = 0;   //肉探针1高温报警
volatile unsigned char global_rtd2_high_temp_alert = 0;   //肉探针1高温报警
volatile unsigned char global_flame_out_alert = 0;        //熄火报警
volatile unsigned char global_mechanical_error_alert = 0; //机械故障
volatile unsigned char global_slow_ignition_alert = 0;    //点火时间过长

volatile char heatrtbeat[500];            //心跳

volatile unsigned char timmer_1_name[100] = "1"; //定时器1名称
volatile unsigned char timmer_2_name[100] = "2"; //定时器2名称
volatile unsigned char auto_cook_state[100] = "NULL"; //自动烧录状态显示

unsigned int menu_inform[11][4]; //菜单模式
volatile char ap_ssid[15] = "BIC_12345678";     //AP SSID
volatile char ap_password[15] = "123456789101"; //AP PASSWORD
volatile signed char wifi_strength;             //wifi信号强度

err_t wireless_state_defate(void)//设置无线状态默认值
{
    wireless_state.station_inform_state = no_inform;
    wireless_state.station_state = disconnect;
    wireless_state.aws_connect_state = disconnect;
    wireless_state.nvs_save_inform = no_inform;
    wireless_state.aws_received_command = no_inform;
    wireless_state.aws_cert = no_inform; //AWS证书
    wireless_state.nvs_clear_inform = no_inform;
    return ESP_OK;
}

//将秒转换成时分秒格式
void ConvertH_M_S(void)
{
    uint32_t hours = 0;
    uint32_t minutes = 0;
    uint32_t seconds = 0;

    seconds = global_timmer_1_set_command;
    hours = (seconds / 3600) % 100;
    minutes = (seconds / 60) % 60;
    seconds = seconds % 60;

    if(global_timmer_1_set != global_timmer_1_set_command)
    {
    }

    hours = 0;
    minutes = 0;
    seconds = 0;

    seconds = global_timmer_2_set_command;
    hours = (seconds / 3600) % 100;
    minutes = (seconds / 60) % 60;
    seconds = seconds % 60;

    if(global_timmer_2_set != global_timmer_2_set_command)
    {
        
    }
}

static void Main_Loop_Task(void* pvParameters)
{
    //编码器处理初始化
    Encoder_Key_Handler = UI_Encoder_Key;
    Encoder_LongKey_Handler = UI_Encoder_KeyLong;
    Encoder_TurnR_Handler = UI_Encoder_R;
    Encoder_TurnL_Handler = UI_Encoder_L;
    
    while (1)
    {
        vTaskDelay(pdMS_TO_TICKS(20));

        EncoderMain();
        esp_task_wdt_reset();

        HeatingFanCtrl();
        ExhaustFanCtrl();
        IgniterCtrl();

        UI_Main();
    }
    vTaskDelete(NULL);
}

//Tick 2ms
static void periodic_timer_callback(void* arg)
{
    static uint8_t temp_10ms = 0;
    static uint16_t temp_1s = 0;

    Buzzer_Clock_2ms();
    EncoderClock();
    ADC_Clock_2ms();
    temp_10ms++;
    if(temp_10ms >= 5)
    {
        temp_10ms -= 5;
        FanCtrlClock();
        HT162X_Lcd_10ms();
        UI_Clock();
        // HT162X_RAM_Tx();
    }
    temp_1s++;
    if(temp_1s >= 500)
    { //tick 1s
        temp_1s -= 500;
        // if(DW_OFF_Count1s < 0xffff) DW_OFF_Count1s++;
        Maintain_Clock();
        
        MemSize("Main");
    }
}


void AWS_Interface_Config(void)
{
    // AWS_Interface.Shuttdown_Handle = UI_TempCtrl_Stop; //熄火
    // // AWS_Interface.Shuttdown_Cancel_Handle = UI_Shuttdown_Cancel; //取消熄火
    // // AWS_Interface.Ignite_Handle = UI_Keyboard_Ignite; //点火
    // AWS_Interface.SetUnit_Handle = UI_SetUnit;
    // AWS_Interface.SetMenu_Handle = UI_SetMenu;
    // AWS_Interface.Set_Alot_State = UI_Alot_StateHandle;

    // AWS_Interface.Get_RTD_Handle = UI_Home_Get_RTDTemp;
    // AWS_Interface.Get_RTDSettings_Handle = I_Lcd_GetRTDSetting;
    // AWS_Interface.Set_RTDSettings_Handle = I_Lcd_SetRTD;

    // AWS_Interface.Get_ProbeA_Handle = UI_ProbeA_GetTemp;
    // AWS_Interface.Get_ProbeB_Handle = UI_ProbeB_GetTemp;
    // AWS_Interface.Get_ProbeASettings_Handle = UI_ProbeA_GetSetting;
    // AWS_Interface.Get_ProbeBSettings_Handle = UI_ProbeB_GetSetting;
    // AWS_Interface.Set_ProbeASettings_Handle = UI_ProbeA_Setting;
    // AWS_Interface.Set_ProbeBSettings_Handle = UI_ProbeB_Setting;

    // AWS_Interface.Get_Timer1_Handle = Timer1_Downcount_Getting;
    // // AWS_Interface.Get_Timer2_Handle = UI_Timer_GetTimer2;
    // AWS_Interface.Get_Timer1Set_Handle = Timer1_GetSetting;
    // // AWS_Interface.Get_Timer2Set_Handle = UI_Timer_GetTimer2Set;
    // AWS_Interface.Set_Timer1_Handle = Timer1_Setting;
    // // AWS_Interface.Set_Timer2_Handle = UI_Timer_SetTimer2;
    // AWS_Interface.Get_Shutoff = UI_Shuttdown_GetTime;


    // AWS_Interface.Get_State_heat = Get_State_Heat;
    // AWS_Interface.Get_State_Grill = Get_State_Grill;
    // AWS_Interface.Get_Unit_Grill = Get_Unit_Grill;
    // AWS_Interface.Get_State_Error = Get_State_Error;
    // AWS_Interface.Get_Timer1_Alert = UI_Timer_GetTimer1Alert;
    // AWS_Interface.Get_ProbeA_Alert = UI_Probe_GetProbeAAlert;
    // AWS_Interface.Get_ProbeB_Alert = UI_Probe_GetProbeBAlert;
}

void app_main()
{
    ESP_LOGE("App_Main", "控制器初始化已完成");
    //Allow other core to finish initialization
    vTaskDelay(pdMS_TO_TICKS(100));
    
    AWS_Interface_Config();
    esp_task_wdt_init(600, false);//设置看门狗

    EncoderInit();
    HT162X_Init();
    UI_Init();
    ADInit();
    FanCtrlInit();
    Buzzer_Init();
    UI_System.OTA_Check = UI_OFF;

    ESP_ERROR_CHECK(wireless_state_defate());         //设置无线状态默认值
    esp_err_t err = nvs_flash_init();
    if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        err = nvs_flash_init();
    }
    ESP_ERROR_CHECK(esp_event_loop_create_default()); //ESP32 事件运行 只能运行一次
    ESP_ERROR_CHECK(mac_address()); //读取basic mac地址

    //创建高精度周期定时器
    esp_timer_handle_t periodic_timer;
    const esp_timer_create_args_t periodic_timer_args = {
        .callback = &periodic_timer_callback,
        .name = "periodic" //名称设置可选,方便调试用
    };
    esp_timer_create(&periodic_timer_args, &periodic_timer);
    esp_timer_start_periodic(periodic_timer, 2000); //相对定时的2ms周期时间

    Factory_Main();
    if(Factory_Enable == 0)
    {
        ESP_ERROR_CHECK(heart_beat_init());    //更新心跳数据
        Gatt_Init();
        ESP_ERROR_CHECK(wifi_sta_init());      //开启apstation模块 并尝试连接wifi
        ESP_ERROR_CHECK(NVS_wifi_inform());    //开启nvs 获取nvs中的wifi信息 更新时记录新的wifi信息
        OTA_Init();
        AWS_Init();

        // xTaskCreate(Main_Loop_Task, "Main_Loop", 1024 * 8, NULL, 13, NULL);
        Main_Loop_Task(NULL);
    }
}
